package com.se.optionView;

import com.se.common.ConnectionType;
import com.se.common.Message;
import com.se.common.MessageType;
import com.se.utils.ClientUtils;
import com.se.utils.ServiceUtils;
import com.se.utils.StageManager;
import com.se.utils.StageType;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Region;
import javafx.stage.Stage;

import java.io.IOException;
import java.net.URL;
import java.util.Objects;
import java.util.ResourceBundle;
import java.util.concurrent.atomic.AtomicReference;

public class FriendRequestController implements Initializable {
    @FXML
    public ListView<String> friendRequestListView;

    @FXML
    public Button btnClose;

    @FXML
    public AnchorPane utilsPane;

    @FXML
    public void btnCloseOnClick() {
        if(StageManager.get(StageType.FRIEND_REQUEST_STAGE) != null) {
            StageManager.get(StageType.FRIEND_REQUEST_STAGE).close();
            StageManager.remove(StageType.FRIEND_REQUEST_STAGE);
        }
    }

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        AtomicReference<Double> offsetX = new AtomicReference<>((double) 0);
        AtomicReference<Double> offsetY = new AtomicReference<>((double) 0);
        utilsPane.setOnMousePressed(event -> {
            offsetX.set(event.getSceneX());
            offsetY.set(event.getSceneY());
        });

        utilsPane.setOnMouseDragged(event -> {
            Stage stage = StageManager.get(StageType.FRIEND_REQUEST_STAGE);
            stage.setX(event.getScreenX() - offsetX.get());
            stage.setY(event.getScreenY() - offsetY.get());
        });

        btnClose.getStylesheets().add(Objects.requireNonNull(getClass().getResource("/com/se/css/close-button.css")).toExternalForm());
        friendRequestListView.getStylesheets().add(Objects.requireNonNull(getClass().getResource("/com/se/css/result-list-view.css")).toExternalForm());
        friendRequestListView.setItems(ServiceUtils.getFriendRequestList());
        friendRequestListView.setCellFactory(cell -> new FriendRequestCell());
    }

    public static class FriendRequestCell extends ListCell<String> {
        @Override
        public void updateItem(String item, boolean empty) {
            super.updateItem(item, empty);

            // 清空单元格内容
            setText(null);
            setGraphic(null);

            if (item == null || empty) return;

            // 主容器使用HBox替代BorderPane
            HBox container = new HBox();
            container.setSpacing(10);
            container.setAlignment(Pos.CENTER_LEFT);
            container.setPadding(new Insets(5));

            // 左侧内容容器
            HBox contentBox = new HBox(5);
            contentBox.setAlignment(Pos.CENTER_LEFT);

            Label nameLabel = new Label(item);
            nameLabel.getStyleClass().add("result-label");
            nameLabel.setStyle("-fx-font-size: 14px;");

            Button btnAgree = createAgreeButton(item);
            Button btnRefuse = createRefuseButton(item);

            Region spacer = new Region();
            HBox.setHgrow(spacer, Priority.ALWAYS);
            contentBox.getChildren().add(nameLabel);
            container.getChildren().addAll(contentBox, spacer, btnAgree, btnRefuse);
            setGraphic(container);
        }

        private Button createRefuseButton(String item) {
            Button button = new Button("拒绝");
            button.getStylesheets().add(Objects.requireNonNull(getClass().getResource("/com/se/css/add-friend-button.css")).toExternalForm());
            button.setOnAction(e -> {
                handleRefuse(item);
                ServiceUtils.removeFriendRequest(item);
            });

            return button;
        }

        private Button createAgreeButton(String item) {
            Button button = new Button("同意");
            button.getStylesheets().add(Objects.requireNonNull(getClass().getResource("/com/se/css/add-friend-button.css")).toExternalForm());
            button.setOnAction(e -> {
                handleAgree(item);
                ServiceUtils.removeFriendRequest(item);
            });

            return button;
        }

        private void handleRefuse(String username) {
            Message message = new Message();
            message.setMsgType(MessageType.MESSAGE_REFUSE_FRIEND_REQUEST);
            message.setSendUser(ServiceUtils.getSpeaker().getUserName());
            message.setReceiveUser(username);
            try {
                ClientUtils.sendMessage(ServiceUtils
                        .getConnection(ConnectionType.BASE_CONNECTION).getSocket(), message);
            } catch (IOException e) {
                /*
                异常处理待优化
                 */
                e.printStackTrace();
            }
        }

        private void handleAgree(String username) {
            Message message = new Message();
            message.setMsgType(MessageType.MESSAGE_AGREE_FRIEND_REQUEST);
            message.setSendUser(ServiceUtils.getSpeaker().getUserName());
            message.setReceiveUser(username);
            try {
                ClientUtils.sendMessage(ServiceUtils
                        .getConnection(ConnectionType.BASE_CONNECTION).getSocket(), message);
            } catch (IOException e) {
                /*
                异常处理待优化
                 */
                e.printStackTrace();
            }
        }
    }
}
